//
//  MJComposeViewController.swift
//  新浪微博
//
//  Created by MaJi on 16/4/17.
//  Copyright © 2016年 MaJi. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class MJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        取消键盘
        textView.resignFirstResponder()
    }
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    func setupUI(){
        
        //设置textView
        setTextView()
//        设置TabBar
        setTabBar()
//        设置ToolBar
        setupToolBar()
//        注册键盘的通知
        registerNotification()
//        设置图片选择的视图
        setPictureSeletor()
    }
//    注册键盘的通知
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    @objc func keyboardChanged(n:NSNotification){
        print(n.userInfo)
        let dict = n.userInfo
        let rect = (dict![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
//        改变tooBar的bottom的值,可以随着键盘回到上面
        let offSetY = -screenHignt + rect.origin.y
        UIView.animateWithDuration(0.25) { () -> Void in
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(offSetY)
            })
            self.view.layoutIfNeeded()
        }
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private func setTabBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回" , target: self, action: "close")
        navigationItem.rightBarButtonItem = rightBarButtonItem
//        设置右边的按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
//        print(navigationItem.titleView)
//        navigationItem.titleView默认是nil,必须赋值之后才可以添加view
//        自定义导航条的titleView
        let myView = UIView()
        myView.frame = CGRect(x: 0, y: 0, width: 220, height: 40)
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView)
            make.top.equalTo(myView)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView)
            make.centerX.equalTo(myView)
        }
        navigationItem.titleView = myView
    }
    func rightBarButtonItemDidClick(){
        print("发送按钮点击")
        guard let token = MJUserAccountViewModel.sharedAccount.account?.access_token else{
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
            return
        }
//        HMNetworkTools,sharedTools.send
        HMNetworkTools.sharedTools.sendStatus(token, status: textView.text , imageList: self.selestorController.imageList) { (result, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            self.dismissViewControllerAnimated(true, completion: nil)
            
        }
    }
    private lazy var rightBarButtonItem:UIBarButtonItem = {
       let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
//        给按钮添加点击事件
        btn.addTarget(self, action: "rightBarButtonItemDidClick", forControlEvents: .TouchUpInside)
//        设置文字
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: .Disabled)
//        设置frame
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        let rightBarButton = UIBarButtonItem(customView: btn)
        return rightBarButton
    }()
    
    private func setTextView(){
        self.view.addSubview(textView)
//        设置布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenHignt/3)
        }
//        添加占位label
        textView.addSubview(placeHolderlabel)
        placeHolderlabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
//        设置textView的代理,实现代理方法,当textView开始输入时,占位label消失,发送按钮可用
        textView.delegate = self
        

    }
    private func setupToolBar(){
        self.view.addSubview(toolBar)

        //        设置toolBar的布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
            //            工具条默认高度是44
        }
        //        添加底部工具条的item
        var items = [UIBarButtonItem]()
        let dictArray = [["imageName":"compose_toolbar_picture","actionName":"selectPicture"],["imageName":"compose_mentionbutton_background","actionName":"selectPicture"],["imageName":"compose_emoticonbutton_background","actionName":"selectEmoticon"],["imageName":"compose_add_background","actionName":"selectPicture"]]
        //        想这样一个方法,有几个不同参数,一般提出出来,搞个字典数组更好,遍历数组,拿到每一个值
        for itemDict in dictArray {
            if let action = itemDict["actionName"]{
                
                let item = UIBarButtonItem(imageName: itemDict["imageName"] , target: self, action: Selector (action))
                items.append(item)
//                将item平均布局的方式,在每个item后面加入一个弹簧,移除最后一个弹簧
//                添加弹簧
                let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
                items.append(space)
//                设置每个item的frame
//                let leftMargin:CGFloat = 8
//                let itemW = (screenWidth - 2*leftMargin)/4
//                let itemH = 44
                
            }
        }
//        移除最后一个弹簧
        items.removeLast()
        toolBar.items = items

    }
//    实现toolBar的方法
    @objc private func selectPicture(){
        print("选择图片")
//        更改图片控制器view的布局
        selestorController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenHignt*2/3)
        }
    }
    @objc private func selectEmoticon(){
        print("选择表情")
    }
    //    懒加载图片选择控制器
    private lazy var selestorController:MJPictureSelectController = MJPictureSelectController()
//    懒加载子视图
//    底部工具条
    private lazy var toolBar = UIToolbar()
    private lazy var titleLabel:UILabel = UILabel(text: "发布微博", textColor: UIColor.darkGrayColor(), fontSize: 16)
    private lazy var nameLabel:UILabel = UILabel(text: MJUserAccountViewModel.sharedAccount.account?.name ?? "", textColor: UIColor.lightGrayColor(), fontSize: 13)
//    设置占位label
    private lazy var placeHolderlabel:UILabel = UILabel(text: "听说下雨天音乐和辣条更配哦", textColor: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var textView:UITextView = {
       let text = UITextView()
        text.font = UIFont.systemFontOfSize(18)
        text.textColor = UIColor.darkGrayColor()
        text.backgroundColor = UIColor(white: 0.9, alpha: 1)
        return text
    }()

}

//实现textView的代理方法
extension MJComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeHolderlabel.hidden = textView.hasText()
        rightBarButtonItem.enabled = textView.hasText()
    }
    
}
//设置图片选择视图的UI
extension MJComposeViewController{
    private func setPictureSeletor(){
        //1.添加子视图控制器
        //以后如果要是使用控制器的视图之前一定要提前持有该控制器  需要添加子视图控制器 --> addChildViewController
        self.addChildViewController(selestorController)
        self.view.addSubview(self.selestorController.view)
//        设置自动布局
        selestorController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    

}


